<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button v-if="isAdmin || isUser" type="primary" @click="handleCreate"> 新增</a-button>
        <a-button type="primary" @click="handleExport"> 导出</a-button>
        <ImpExcel @success="loadDataSuccess">
          <a-button> 导入</a-button>
        </ImpExcel>
        <a-button v-if="isAdmin || isAudit" type="error" @click="batchDelete"> 批量删除</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑',
              onClick: handleEdit.bind(null, record),
              ifShow: isAdmin || isUser,
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
              ifShow: isAdmin || isAudit,
            },
          ]"
        />
      </template>
    </BasicTable>
    <FixResidentDrawer @register="registerDrawer" @success="handleSuccess" />
    <ImportDrawer @register="registerImportDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import FixResidentDrawer from './FixResidentDrawer.vue';
  import { ImpExcel } from '/@/components/Excel';
  import ImportDrawer from './ImportDrawer.vue';
  import { columns, searchFormSchema } from './fixResident.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { FixResidentIDType } from '/@/api/opms/model/FixResidentModel';
  import {
    deleteFixResidentBatch,
    exportRewriteExcel,
    getFixResidentPage,
  } from '/@/api/opms/fixResident';
  import { useUserStore } from '/@/store/modules/user';
  import { ref } from 'vue';
  import { ExcelData } from '/@/components/Excel';

  const { isAdmin, isAudit, isUser, getUserInfo } = useUserStore();

  // 初始化弹出模块
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerImportDrawer, { openDrawer: openImportDrawer }] = useDrawer();
  // 消息提示
  const { createMessage, createConfirm } = useMessage();
  const tableListRef = ref<
    {
      title: string;
      columns?: any[];
      dataSource?: any[];
    }[]
  >([]);
  // 初始化表格
  const [
    registerTable,
    { reload, getSelectRows, clearSelectedRowKeys, getForm, getPaginationRef },
  ] = useTable({
    title: '居民管理列表',
    api: getFixResidentPage,
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    clickToRowSelect: false,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleCreate() {
    openDrawer(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  }

  async function handleDelete(record: Recordable) {
    let params: Array<FixResidentIDType> = [];
    params.push(record.id);
    await deleteFixResidentBatch(params);
    createMessage.success('删除成功');
    await reload();
  }

  function handleSuccess() {
    reload();
  }

  async function handleExport() {
    //获取搜索框数据
    const form = getForm();
    //获取分页数据
    const pagination: any = getPaginationRef();
    //合并数据
    let params = form.getFieldsValue();
    params.current = pagination.current;
    params.size = pagination.defaultPageSize;
    console.log('-->', params, pagination);
    const res = await exportRewriteExcel(params);
    //将文件流转换成blob
    let blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    });
    let downloadElement = document.createElement('a');
    let href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement); //移除元素；防止连续点击创建多个a标签
    window.URL.revokeObjectURL(href);
  }

  /*导入*/
  async function loadDataSuccess(excelDataList: ExcelData[]) {
    for (const excelData of excelDataList) {
      const {
        header,
        results,
        meta: { sheetName },
      } = excelData;
      const columns: BasicColumn[] = [];
      for (const title of header) {
        columns.push({ title, dataIndex: title });
      }
      tableListRef.value.push({ title: sheetName, dataSource: results, columns });
    }
    const tableList = tableListRef.value;
    tableListRef.value = [];
    openImportDrawer(true, {
      tableList,
    });
  }

  // 批量删除
  async function batchDelete() {
    let params: Array<FixResidentIDType> = [];
    for (let _item of getSelectRows()) {
      params.push(_item.id);
    }
    if (params.length <= 0) {
      createMessage.warning('请至少选择一条记录');
      return;
    }

    createConfirm({
      iconType: 'warning',
      title: () => '删除提示',
      content: () => '确定要删除选中项吗！',
      okText: () => '立即删除',
      cancelText: () => '取消',
      onOk: async () => {
        await deleteFixResidentBatch(params);
        createMessage.success('删除成功');
        // 清空选择行
        clearSelectedRowKeys();
        await reload();
      },
    });
  }
</script>
<script lang="ts">
  export default { name: 'FixResident' };
</script>
